<template>
	<view class="con">
		<view class="form_list" v-if="!loading">
			<!-- <view class="item" v-for="item in fieldData">
				<view class="label">
					{{item.name}}
				</view>
				<view class="com">
					<template v-if="item.type=='input'">
						<uni-easyinput v-model="value" :placeholder="item.hint" :style="styles"></uni-easyinput>
					</template>
					<template v-if="item.type=='multi_input'">
						<uni-easyinput  type="textarea" v-model="value" :placeholder="item.hint" :style="styles"></uni-easyinput>
					</template>
					<template v-if="item.type=='group_select'">
						 <uni-data-select v-model="value"  :localdata="item.option" ></uni-data-select>
					</template>
					<template v-if="item.type=='file'">
						<uni-file-picker 
							v-model="imageValue" 
							fileMediatype="image" 
							mode="grid" 
							@select="select" 
							@progress="progress" 
							@success="success" 
							@fail="fail" 
						/>
					</template>
				</view>
				
			</view> -->
			<!-- ,{_tdata:item,validateFunction:validateFunction} -->
			<uni-forms ref="form" :modelValue="formData" :label-width="100">
				<uni-forms-item :label="item.name" :name="'set_id'+item.id" :required="item.require==1"
					:rules="[{required:item.require==1,errorMessage:formatStr(item.type)+item.name}]"
					v-for="item in fieldData">
					<template v-if="item.type=='input'">
						<uni-easyinput v-model="formData['set_id'+item.id]" :placeholder="item.hint"
							:style="styles"></uni-easyinput>
					</template>
					<template v-if="item.type=='multi_input'">
						<uni-easyinput type="textarea" v-model="formData['set_id'+item.id]" :placeholder="item.hint"
							:style="styles"></uni-easyinput>
					</template>
					<template v-if="item.type=='group_select'">
						<uni-data-select v-model="formData['set_id'+item.id]"
							:localdata="item.option"></uni-data-select>
						<div v-if="item.hint!=''" class="hints">{{ item.hint }}</div>
					</template>
					<template v-if="item.type=='file'">
						<upLoadFile :fileExtname="upDataType" :limit="item.limit==0?9:item.limit" :fileData="formData['set_id'+item.id]" @update="getFiles($event,'set_id'+item.id)"></upLoadFile>
						<div v-if="item.hint!=''" class="hints">{{ item.hint }}</div>
					</template>
					<template v-if="item.type=='file_audio'">
						<div v-if="formData['set_id'+item.id].url!=''">
							<!-- <audio class="my_audio" :poster="setData.banner" :name="formData['set_id'+item.id].name" :src="formData['set_id'+item.id].url"   controls></audio> -->
							<audioPlay :poster="setData.banner" :info="formData['set_id'+item.id]" :src="formData['set_id'+item.id].url" ></audioPlay>
						</div>
						<upLoadAudio v-if="formData['set_id'+item.id].url==''" :fileExtname="['.mp3','.wav','.flac','.aac','.wav']" :limit="item.limit==0?9:item.limit" :fileData="[]" @update="getFilesAudio($event,'set_id'+item.id)"></upLoadAudio>
						<div style="color: #1895ff;" v-else @click="delMusic('set_id'+item.id)">删除音乐</div>
						<div v-if="item.hint!=''" class="hints">{{ item.hint }}</div>
					</template>
				</uni-forms-item>
			</uni-forms>
		</view>
<!-- 		<view class="btn_edit">
			重新编辑
		</view> -->
		<view class="btn_submit" @click="openConfirm">
			提交
		</view>
		
		
		<view class="modal_rule fadeIn"  @touchmove.prevent v-if="ruleModal">
			
			<view class="content">
				<scroll-view  class="scroll-view"  scroll-y="true" >
					<view class="title">
						报名申明
					</view>
					<view>
						 {{activityData.settings.vote_reg_desc}}
					</view>
					<!-- <view class="_c" v-html="data.activity_rules"></view> -->
				</scroll-view>
				<view class="btn">
					<view class="close" @click="ruleModal = false">关闭</view>
					<view class="confirm" @click="submit">确认</view>
				</view>
			</view>
			
		</view>
		<view class="modal_rule fadeIn"  @touchmove.prevent v-if="successJoin">
			<view class="content s_">
				<view class="title">{{wid?'修改成功':'报名成功'}}</view>
				<image class="success" :src="activityData.settings.vote_reg_popup_ad_image"></image>
				
				<view class="btn">
					<view class="close" @click="next(1)">返回</view>
					<view v-if="regData.get_chance>0" class="confirm" @click="next(2)">前去抽奖</view>
				</view>
			</view>
			
		
		</view>
	</view>
</template>

<script>
	import { getVotePrereg,postVotePrereg ,getVoteGroup,getVoteUserWorksDetail,getVotePreAdd} from '@/api/api'
	import {proxyShareFun,isQianfan,isWeiXin} from '@/until/QFH5.js'
	import upLoadAudio from '@/components/upLoadFile/upLoadAudio.vue'
	export default {
		components:{upLoadAudio},
		computed: {
			setData(){
				let key = this.$route.query.id + 'ActivityData'
				let data = JSON.parse(localStorage.getItem(key))
				return data.settings
			}
		},
		data() {
			//无效验证
			const validateFunctions = function(rule, value, data, callback) {
				console.log('123456++', rule, value, )
				let key = 'set_id' + rule._tdata.id
				let str = ''
				switch (rule._tdata.type) {
					case 'input':
					case 'multi_input':
						str = '请输入';
						break;
					case 'group_select':
						str = '请选择';
						break;
					case 'file':
						str = '请上传';
						break;
				}
				console.log('++++', data[key])
				if (rule._tdata.require == 1 && (data[key] == '' || data[key].length == 0)) {
					callback(str)
				}
				return true
			}
			return {
				activityData:'',
				actid: '',
				wid:'',
				fieldData: [],
				worksLimit: 0, //作品上传限制
				formData: {},
				styles: {
					color: '#222',
					borderColor: '#fff'
				},
				validateFunction: validateFunctions,
				isEdit:false,
				ruleModal:false,
				loading:true,
				
				needConfirm:false,
				successJoin:false,
				regData:{get_chance:0},
				
				upDataType:['.jpeg','.png','.jpg','.gif','.mp4','.avi','.mov','.rmvb','.flv','.rm','.3gp'],
			}
		},
		methods: {
			next(_v){
				if(_v==1){
					let url = '/plugin/pages/index?type=vote&plugin=vote&id='+this.actid
					this.$navigateTo({url:url})
				}else{
					let url ='/plugin/pages/vote/prize?id='+this.actid
					this.$navigateTo({ url:url})
				}
			},
			openConfirm(){
				this.$refs.form.validate().then(res => {
					if(this.activityData.settings.vote_reg_desc!=''){
						this.ruleModal = true
					}else{
						this.submit()
					}
				}).catch(err => {
					// console.log('表单错误信息：', err);
					uni.showToast({
						title:'有信息未填写，请重新检查表单！',
						icon:'none'
					})
				})
			},
			formatStr(type) {
				let str = ''
				switch (type) {
					case 'input':
					case 'multi_input':
						str = '请输入';
						break;
					case 'group_select':
						str = '请选择';
						break;
					case 'file':
						str = '请上传';
						break;
				}
				return str
			},
			submit() {
				// console.log((this.formData))
				// this.$refs.form.validate().then(res => {
					let postObj = {}
					let arr = []
					Object.keys(this.formData).map(item=>{
					    if(item.indexOf('set_id')>-1){
							let id = item.replace(/set_id/g,'')
							let aliasIndex = this.fieldData.find(item=>item.id == id)
					        let extObj = {
					                field_id:id,
									alias:aliasIndex.alias,
					                value:this.formData[item]
					        }
					        arr.push(extObj)
					        delete this.formData[item]
					    }
					})
					postObj.fields_values = JSON.stringify(arr)
					postObj.actid = this.actid
					postObj.plugin = 'vote'
					if(this.wid ){
						postObj.works_id = this.wid 
					}
					postVotePrereg(postObj).then(res=>{
						if(res.code==0){
							this.regData = res.data
							this.ruleModal = false
							 this.successJoin = true
						}else{
							uni.showToast({
								title:res.text,
								icon:'none'
							})
						}
					})
				// }).catch(err => {
				// 	console.log('表单错误信息：', err);
				// })
			},
			delMusic(id){
				this.formData[id] ={name:'',url:''}
			},
			 getFilesAudio(e,id){
				this.formData[id] = {
					url:e[0].url,
					name:e[0].name
				}
			 },
			 getFiles(e,id){
				 let list  = e
				 let arr = []
				 list.map(item=>{
					let obj = {
						url:item.url,
						width:item.width,
						height:item.height
					}
					 arr.push(obj)
				 })
				 this.formData[id] = arr
			 },

			 
			init() {
				getVotePrereg({ plugin: 'vote', actid: this.actid ,works_id:this.wid}).then(res => {
					this.worksLimit = res.data.works_limit==0?100:res.data.works_limit
					this.fieldData = res.data.field.reverse()
					this.fieldData.map(item => {
						this.$set(this.formData, 'set_id' + item.id, "")
						item.required = item.required == 1 ? true : false
						if (item.type == 'group_select') {
							
							let valueArr = item.choices.split('\n')
							if(item.alias=='group_id'){
								valueArr = item.groups
							}
							let arr = []
							valueArr.map(child => {
								let obj = { value: child, text: child }
								if(item.alias=='group_id'){
									obj =  { value: child.id, text: child.name }
								}
								arr.push(obj)
							})
							item.option = arr
						}
						if (item.type == 'file') {
							this.formData['set_id' + item.id] = []
						}
						if (item.type == 'file_audio') {
							this.formData['set_id' + item.id] = {name:'',url:''}
						}
					})
					
					
					if(this.isEdit){
						this.initDetail()
					}else{
						this.loading = false
					}
				})
			},
			initDetail(){
				 getVotePreAdd({ plugin: 'vote', actid: this.actid,works_id:this.wid}).then(res=>{
					 if(res.code==0){
						res.data.works_fields.map(item=>{
							this.formData['set_id' + item.id] = item.field_value
						})
						res.data.works_info.ext_fields_val.map(item=>{
							this.formData['set_id' + item.field_id] = item.value
						})
						this.loading = false
					 }
				 })
			},
		},
		mounted() {
			this.$setTitle('我要报名')
			this.activityData = localStorage.getItem(this.actid+'ActivityData') || null
			if(this.activityData){
				this.activityData = JSON.parse(this.activityData)
			}
			if(!this.activityData.settings.works_video){
				this.upDataType = ['.jpeg','.png','.jpg','.gif']
			}
			//页面不可以被直接打开
			let url = window.location.origin+'/plugin-view/?type=vote&plugin=vote&id='+this.actid
			let data =  this.activityData
			proxyShareFun(data.settings.title||data.settings.desc,data.settings.image,data.settings.desc,url)
			this.init()
		},
		onLoad(op) {
			this.actid = op.id
			this.isEdit= op.isEdit || false
			this.wid = op.work_id
		}
	}
</script>

<style lang="scss" scoped>
.my_audio{
	width: 430rpx!important;
	/deep/ .uni-audio-default{
		width: 430rpx!important;
		min-width: 430rpx!important;
		max-width: 430rpx!important;
	}
}
	.hints{
		color: #999;
		font-size: 24rpx;
		margin-top: 4rpx;
	}
	.con {
		background: #f7f7f7;
		padding: 1rpx 0 60rpx 0;
		margin-top: -1rpx;
		min-height: 100vh;
		.form_list {
			width: 634rpx;
			background: #FFFFFF;
			padding: 20rpx 30rpx 20rpx 38rpx;
			border-radius: 20rpx;
			background-color: #FFFFFF;
			margin: 33rpx auto 0;

			.item {
				display: flex;
				justify-content: flex-start;
				align-items: center;

				&:not(:last-child) {
					// border-bottom: 1rpx solid #E5E5E5;
				}

				padding: 36rpx 0;

				.label {
					width: 200rpx;
					height: 45rpx;
					line-height: 45rpx;
					font-size: 32rpx;
					font-family: PingFang SC-Medium, PingFang SC;
					font-weight: 500;
					color: #222222;
				}

				.com {
					width: 426rpx;
					margin-left: 8rpx;
				}
			}
		}

		.btn_edit {
			width: 692rpx;
			height: 88rpx;
			line-height: 90rpx;
			background: #FFFFFF;
			border-radius: 45rpx;
			border: 1rpx solid #FE7F00;
			font-size: 34rpx;
			font-family: PingFang SC-Medium, PingFang SC;
			font-weight: 500;
			color: #FE7F00;
			text-align: center;
			margin: 30rpx auto 0;
		}

		.btn_submit {
			width: 694rpx;
			height: 90rpx;
			line-height: 90rpx;
			background: #FE7F00;
			border-radius: 45rpx;
			color: #fff;
			text-align: center;
			margin: 30rpx auto 0;
		}
	}
	.modal_rule{
		position: fixed;
		left: 0;
		top: 0;
		width: 100%;
		height: 100%;
		background: rgba(0,0,0,0.7);
		z-index: 99;
		.scroll-view{
			height: 100%; 
			overflow-y: scroll;
			max-height: 70vh;
		}
		.content{
			
			margin: 164rpx auto 0;
			width: 634rpx;
			padding: 30rpx 30rpx 40rpx;
			background: #FFFFFF;
			border-radius: 30rpx;
			overflow: scroll;
			.title{
				text-align: center;
				height: 50rpx;
				line-height: 50rpx;
				font-size: 36rpx;
				font-family: PingFang SC-Bold, PingFang SC;
				font-weight: bold;
				color: #222222;
				margin-bottom: 30rpx;
			}
			.c_{
				font-size: 30rpx;
			}
		
			.btn{
				margin-top: 30rpx;
				height: 90rpx;
				display:flex;
				justify-content: center;
				align-items: center;
				&>view{
					width: 290rpx;
					height: 90rpx;
					line-height: 90rpx;
					background: #FE7F00;
					border-radius: 45rpx;
					color: #FFFFFF;
					font-size: 34rpx;
					font-family: PingFang SC-Bold, PingFang SC;
					font-weight: bold;
					text-align: center;
					margin: 0 10rpx;
				}
				.close{
					width: 284rpx;
					height: 84rpx;
					line-height: 84rpx;
					border: 3rpx solid #717D8F;
					background:none;
					color: #677594;
				}
			}
		}
		.s_{
			text-align: center;
			.success{
				width: 200rpx;
				height: 200rpx;
				margin: 30rpx auto 0;
			}
		}
	}
</style>